<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2019/5/18
 * Time: 下午6:09
 */

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;

class GiftBag extends Base
{
    protected $table = 'gift_bag';
    protected $primaryKey = 'id';
    protected $giftLibraryTable = 'gift_library';

    protected $activityConnect = 'activity';
    protected $customTable = "custom";

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 变更背包礼物
     * @param int $userId  用户ID
     * @param int $toUserId  获取礼物用户ID，获得礼物设置为0
     * @param int $giftId 礼物ID
     * @param int $change 变更礼物的数量 送礼物时为负数
     * @param int $platformType 来源类型 枚举在 bagGiftPlatformType()
     * 
     */
    public function inc($userId, $toUserId, $giftId, $change, $platformType=0, $dataId=0)
    {
        // 此处执行标识
        $flag = true;

        // 更新背包剩余数
        $increment = DB::table($this->table)
            ->where('user_id', '=', $userId)
            ->where('gift_id', '=', $giftId)
            ->increment('avail', $change, ['update_timestamp' => time()]);

        if (!$increment) {
            // 创建背包默认数据
            $insertBag = DB::table($this->table)->insert([
                'user_id' => $userId,
                'gift_id' => $giftId,
                'avail' => $change,
                'create_timestamp' => time(),
                'update_timestamp' => time()
            ]);
            if (!$insertBag) {
                $flag = false;
            }
        }

        if ($flag) {
            // 创建背包日志
            $insertBagLog = DB::table('gift_bag_log')->insert([
                'user_id' => $userId,
                'gift_id' => $giftId,
                'to_user_id' => $toUserId,
                'change' => $change,
                'avail' => 0,
                'platform_type' => $platformType,
                'data_id' => $dataId,
                'create_timestamp' => time()
            ]);
            if (!$insertBagLog) {
                $flag = false;
            }
        }

        return $flag;
    }

    //背包礼物来源类型
    public function bagGiftPlatformType(){
        //注意 10000到99999 是给自定义活动的
        $data = [
            ['platform_type' => 0,'name' => '送礼'],
            ['platform_type' => 12,'name' => '减少礼物抵扣券'],
            ['platform_type' => 13,'name' => '增加礼物抵扣券'],
            ['platform_type' => 101,'name' => '娱乐等级奖励'],
            ['platform_type' => 1000,'name' => '许愿池-普通池'],
            ['platform_type' => 1001,'name' => '许愿池-高级池'],
            ['platform_type' => 1011,'name' => '许愿转盘'],
            ['platform_type' => 2001,'name' => '周星榜'],
            ['platform_type' => 2002,'name' => '西天取经'],
            ['platform_type' => 2007,'name' => '三国群英押注'],
            ['platform_type' => 2009,'name' => '三国群英押注撤回'],
            ['platform_type' => 2010,'name' => '三国群英奖励'],
            ['platform_type' => 2012,'name' => '人气票'],
            ['platform_type' => 2013,'name' => '热度卡'],
            ['platform_type' => 3001,'name' => '回归活动签到'],
            ['platform_type' => 3002,'name' => '回归活动任务'],
            ['platform_type' => 4000,'name' => '万神殿-1'],
            ['platform_type' => 4001,'name' => '万神殿-2'],
            ['platform_type' => 4002,'name' => '万神殿-3'],
            ['platform_type' => 4003,'name' => '万神殿-4'],
            ['platform_type' => 4010,'name' => '万神殿-1擂主'],
            ['platform_type' => 4011,'name' => '万神殿-2擂主'],
            ['platform_type' => 4012,'name' => '万神殿-3擂主'],
            ['platform_type' => 4013,'name' => '万神殿-4擂主'],
            ['platform_type' => 5001,'name' => '快捷添加'],

        ];

        $customList = DB::connection($this->activityConnect)->table($this->customTable)->select(['id', 'game_name'])->get();
        $customList = objToArray($customList);
        foreach($customList as $val) {
            $item = ['platform_type' => $val['id'],'name' => '自定义活动|'.$val['id'].'|'.$val['game_name']];
            $data[] = $item;
        }

        return $data;
    }

    /**
     * 礼物背包列表
     * */
    public function giftBagList($condition = [], $page = 1, $limit = 10)
    {
        $result = DB::table($this->table)
            ->where($condition)
            ->leftJoin($this->giftLibraryTable, $this->table . '.gift_id', '=', $this->giftLibraryTable . '.gift_id')
            ->orderBy($this->giftLibraryTable . '.price', 'asc')
            ->offset($limit * ($page - 1))
            ->limit($limit)
            ->get([
                $this->table . '.gift_id',
                $this->table . '.user_id',
                $this->table . '.avail',
                $this->giftLibraryTable . '.name',
                $this->giftLibraryTable . '.image',
                $this->giftLibraryTable . '.price',
                $this->giftLibraryTable . '.gift_type', // 查询礼物类型
                $this->giftLibraryTable . '.animate_resource',// 动画资源包链接
            ]);

        $result = self::objToArray($result);

        // 增加图片URL domain
        foreach ($result as $key => $value) {
            if (!empty($value['animate_resource'])) {
                $result[$key]['animate_resource'] = getPicDomain() . $result[$key]['animate_resource'];
            }
            $result[$key]['image'] = getPicDomain() . $result[$key]['image'];
        }

        //根据字段 price 对数组$data进行降序排列
//        $price = array_column($result, 'price');
//        array_multisort($price, SORT_ASC, $result);

        return $result;
    }

    /**
     * 礼物背包总数
     * */
    public function giftBagTotal($condition = [])
    {
        $count = DB::table($this->table)
            ->where($condition)
            ->count('gift_id');
        return $count;
    }

    /**
     * 查询
     * */
    public function get($params = [], $isSingle = false)
    {
        if ($isSingle) {
            $result = DB::table($this->table)->where($params)->first();
            return self::objToArray($result);
        } else {
            $result = DB::table($this->table)->where($params)->orderBy('id', 'desc')->get()->toArray();
            return self::objToArray($result);
        }
    }


    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function getAll($userId)
    {
        $result = DB::table($this->table)
            ->where([['user_id', '=', $userId], ['avail', '>', 0]])
            ->leftJoin($this->giftLibraryTable, $this->table . '.gift_id', '=', $this->giftLibraryTable . '.gift_id')
            ->orderBy($this->giftLibraryTable . '.price', 'asc')
            ->get([
                $this->table . '.gift_id',
                $this->table . '.user_id',
                $this->table . '.avail',
                $this->giftLibraryTable . '.name',
                $this->giftLibraryTable . '.image',
                $this->giftLibraryTable . '.price',
                $this->giftLibraryTable . '.gift_type', // 查询礼物类型
                $this->giftLibraryTable . '.animate_resource',// 动画资源包链接
                $this->giftLibraryTable . '.gift_label_id',
                $this->giftLibraryTable . '.wealth_num',
            ]);

        $result = self::objToArray($result);

        // 增加图片URL domain
        foreach ($result as $key => $value) {
            if (!empty($value['animate_resource'])) {
                $result[$key]['animate_resource'] = getPicDomain() . $result[$key]['animate_resource'];
            }
            $result[$key]['image'] = getPicDomain() . $result[$key]['image'];
        }
        return $result;
    }
     
    //获取指定礼物所持数量
    public function getNewGiftArr($userId, $giftId){
        $result = DB::table($this->table)
            ->where([['user_id', '=', $userId], ['avail', '>', 0]])
            ->whereIn($this->table . '.gift_id',$giftId)
            ->leftJoin($this->giftLibraryTable, $this->table . '.gift_id', '=', $this->giftLibraryTable . '.gift_id')
            ->orderBy($this->giftLibraryTable . '.price', 'asc')
            ->get([
                $this->table . '.gift_id',
                $this->table . '.user_id',
                $this->table . '.avail',
                $this->giftLibraryTable . '.name',
                $this->giftLibraryTable . '.image',
                $this->giftLibraryTable . '.price',
                $this->giftLibraryTable . '.gift_type', // 查询礼物类型
                $this->giftLibraryTable . '.animate_resource',// 动画资源包链接
                $this->giftLibraryTable . '.gift_label_id',
            ]);

        $result = self::objToArray($result);
        if(empty($result)){
            $result = DB::table($this->giftLibraryTable)->whereIn('gift_id',$giftId)->get();
            $result = self::objToArray($result);
        }
        // 增加图片URL domain
        foreach ($result as $key => $value) {
            if (!empty($value['animate_resource'])) {
                $result[$key]['animate_resource'] = getPicDomain() . $result[$key]['animate_resource'];
            }
            $result[$key]['image'] = getPicDomain() . $result[$key]['image'];
        }
        return $result;
    }
}
